<?php

namespace app\giftcard\logic;

use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class GiftcardLogic extends BasicLogic
{
    public function __construct()
    {
        
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $batch = $params['batch'] ?? "";
        $code = $params['code'] ?? "";
        $limit = $params['limit'] ?? 10;
        $where = [];

        if (!empty($batch)) {
            if ($batch == 'API记录') {
                $where[] = ['type', '=', "API"];
            }else{
                $where[] = ['batch', '=', $batch];
            }
        }else{
            $where[] = ['type', '=', "API"];
        }
        if (!empty($code)) {
            $where[] = ['code', 'like', "%" . $code . "%"];
        }
        
        $list = Db::name('gift_card')
            ->where($where)
            ->order('created_at desc')
            ->paginate($limit);

        $lists = $list->items();

        foreach ($lists as $k=>$v) {
            if($v['code'] == ""){
                $lists[$k]['code'] = $v['last_characters'] ?? "";
            }
            switch ($v['status']) {
                case '0':
                    $lists[$k]['status'] = '待生成';
                    break;
                case '1':
                    $lists[$k]['status'] = '已完成';
                    break;
                case '2':
                    $lists[$k]['status'] = '失败';
                    break;
                default:
                    $lists[$k]['status'] = '待生成';
            }
            if($v['type'] == 'API'){
                $lists[$k]['status'] = '已完成';
            }
            
        }
        
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['券码', 'code'];
        $header[] = ['币种', 'currency'];
        $header[] = ['金额', 'balance'];
        $header[] = ['初始值', 'initial_value'];
        $header[] = ['创建时间', 'created_at'];
        
        $batch = $params['batch'] ?? "";
        $code = $params['code'] ?? "";
        $where = [];

        if (!empty($batch)) {
            if ($batch == 'API记录') {
                $where[] = ['type', '=', "API"];
            }else{
                $where[] = ['batch', '=', $batch];
            }
        }else{
            $where[] = ['type', '=', "API"];
        }
        if (!empty($code)) {
            $where[] = ['code', 'like', "%" . $code . "%"];
        }
        
        $lists = Db::name('gift_card')
            ->where($where)
            ->order('created_at desc')
            ->select()->toarray();

        foreach ($lists as $k=>$v) {
            if($v['code'] == ""){
                $lists[$k]['code'] = $v['last_characters'] ?? "";
            }
        }

        $fileName = "giftcard" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    public function add($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        if ($data['shop_name'] == "") {
            return json(DefaultResponse(201, false, '店铺不能为空!', null));
        }
        if ($data['balance'] <= 0) {
            return json(DefaultResponse(201, false, '金额不能为空!', null));
        }
        if ($data['initial_value'] <= 0) {
            return json(DefaultResponse(201, false, '金额不能为空!', null));
        }
        $system_admin = Db::name('system_admin')->where('id',$data['admin_id'])->find();
        if (!$system_admin) {
            return json(DefaultResponse(201, false, '请重新登录!', null));
        }
        $shop_name = $data['shop_name'];
        switch ($shop_name) {
            case 'SheCurve':
                $shop_id = 17;
                break;
            case 'woobilly':
                $shop_id = 21;
                break;
            case 'LilyLove':
                $shop_id = 18;
                break;
            case 'Kisslove':
                $shop_id = 22;
                break;
            default:
                $shop_id = 0;
        }

        //生成批次号
        $currentMonth = date('m');
        $currentYear  = date('Y');
        $currentday   = date('d');
        $batch = $currentYear.$currentMonth.$currentday.random_int(100, 999).$data['admin_id'];

        //手动录入批次号
        $row = [
            'admin_id' => $data['admin_id'] ?? '',
            'admin_name' => $system_admin['username'] ?? '',
            'created_at' => date('Y-m-d H:i:s', time()),
            'batch' => $batch ?? ''
        ];
        
        $result = Db::name('gift_card_batch')->insert($row);
        if ($result == false) {
            return json(DefaultResponse(200, true, '批次号添加失败!', null));
        }

        //手动录入代金券
        $num = $data['num'] ?? 0;
        $insert = [];
        for($i = 0; $i < $num; $i++) {
            //随机生成code码
            $code = $this->generateUniqueCode();
            $insert[] = [
                'shop_name' => $shop_name,
                'shop_id' => $shop_id,
                'balance' => $data['balance'] ?? 0,
                'currency' => $data['currency'] ?? '',
                'initial_value' => $data['initial_value'] ?? 0,
                'created_at' => date('Y-m-d H:i:s', time()),
                'code' => $code ?? '',
                'type' => "手动录入",
                'batch' => $batch ?? '',
            ];
        }
        if($insert) {
            $result = Db::name('gift_card')->insertAll($insert);
        } else {
            return json(DefaultResponse(201, false, '数据为空!', null));
        }

        if ($result !== false) {
            return json(DefaultResponse(200, true, '添加成功!', null));
        } else {
            return json(DefaultResponse(201, false, '添加失败!', null));
        }
    }

    public function generateUniqueCode() {
        // 定义一个包含所有大写字母的数组
        $letters = range('A', 'P');
        // 打乱数组顺序
        shuffle($letters);
        // 将打乱后的数组分割成四组，每组四个字母
        $groups = array_chunk($letters, 4);
        // 将每组字母拼接成字符串，并用空格分隔
        $code = implode(' ', array_map(function($group) {
            return implode('', $group);
        }, $groups));
        return $code;
    }

    public function find($params = [])
    {
        $data = [
            'list' => [],
            'total' => 0,
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $id = $data['id'];
        if (empty($id)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        $result = false;

        try {
            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }

    

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function batch($params = [])
    {
        $date = $params['date'] ?? "";
        $limit = $params['limit'] ?? 10;
        $where = [];

        if (!empty($date)) {
            $where[] = ['timedate', '=', strtotime($date)];
        }
        $list = Db::name('gift_card_batch')
            ->field('id, batch, admin_name, created_at')
            // ->where($where)
            ->order('created_at desc')
            ->paginate($limit);

        $lists = $list->items();
        foreach ($lists as $k=>$v) {
            $lists[$k]['isActive'] = false;
        }
        
        // $Initial[] = [
        //     'id' => 0,
        //     'batch' => 'API记录',
        //     'isActive' => true,
        //     'admin_name' => '张恒',
        // ];
        // $lists = array_merge($Initial, $lists);
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    
}
